#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :api_02.py
# @Time      :2024/11/9 0:44
# @Author    :zhou_yi
from datetime import datetime
from fastapi import APIRouter, UploadFile, File, Form

from models.BaseModels import ClearWasterRecordBaseModel as cwrBM
from service.fn_db import clearWasterRecordsDB as cwrDB, clearWasterRecordsFS as cwrFS
# from service.fn_file import save_image_to_gfs_cwrs

a03 = APIRouter()


# 根据fk 查点位清运记录
@a03.get('/cwr/{fk}')
async def fetch_cwr_by_fk(fk: str):
    _res = await cwrDB.fetch_by_fk(fk)
    cwr: list[cwrBM] = [cwrBM(**itm) for itm in _res]
    return cwr


# 根据时间范围查询某点位清运记录
@a03.get('/cwr_timeframe/{fk}')
async def fetch_cwr_timeframe(fk: str, start: str, end: str):
    _fmt = '%Y-%m-%d'
    start = datetime.strptime(start, _fmt)
    end = datetime.strptime(end, _fmt)

    _res = await cwrDB.fetch_by_fk_and_timeframe(fk, start, end)
    cwr: list[cwrBM] = [cwrBM(**itm) for itm in _res]
    return cwr


# 插入一条清运记录
@a03.post('/cwr')
async def insert_one_cwr(cwr: cwrBM):
    res: bool = await cwrDB.insert_one(cwr.dict())
    return res


# 插入点位的图片存入数据库
@a03.post('/cwr_imgs/{pointId}/{dt}')
async def insert_one_cwr_images(pointId: str, dt: str, files: list[UploadFile] = File(...)):
    if files:
        data = [await f.read() for f in files]
        res: int = await cwrFS.insert_many_by_fk_date(pointId, dt, data)
        # dt = datetime.strptime(dt, '%Y-%m-%d')
        # for idx, file in enumerate(files):
        #     name = f"{pointId}_{dt.year}_{dt.month}_{dt.day}_{idx}.png"
        #     b = await file.read()
        #     _res = await save_image_to_gfs_cwrs(b=b, name=name)
        return res
    else:
        return False


# 修改记录
@a03.put('/cwr/{pointNanem}/{dt}')
async def update_cwrs(pointName: str, dt: str, data: dict = Form(...), files: list[UploadFile] = File(None)):
    ...


# 删除记录 日期为空 删除点位所有记录
@a03.delete('/point/{pointName}/{dt}')
async def delete_cwrs(pointName: str, dt: str = None):
    ...


# 插入多条清运记录
@a03.post('/cwrs')
async def insert_many_cwrs(cwrs: list[cwrBM]):
    cwrs = [itm.dict() for itm in cwrs]
    res: bool = await cwrDB.insert_many(cwrs)
    return res


if __name__ == '__main__':
    ...
